package com.siyoumi.app.modules.mall2.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.siyoumi.app.entity.M2Spu;
import com.siyoumi.app.modules.mall2.service.SvcM2Cart;
import com.siyoumi.app.modules.mall2.service.SvcM2Spu;
import com.siyoumi.app.service.M2SpuService;
import com.siyoumi.component.http.InputData;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/wxapp/mall2/api")
public class ApiM2Spu
        extends ApiM2Base {
    /**
     * 商品列表
     */
    @RequestMapping("spu_list")
    public XReturn spuList() {
        M2SpuService appSpu = SvcM2Spu.getApp();

        QueryWrapper<M2Spu> query = SvcM2Spu.getBean().listQuery(InputData.fromRequest());
        query.eq("mspu_enable", 1);
        List<Map<String, Object>> list = appSpu.getMaps(query);

        getR().setData("list_data", list);

        return getR();
    }

    /**
     * 商品详情
     */
    @RequestMapping("spu_info")
    public XReturn spuInfo() {
        String spuId = getRequest().getParameter("spu_id");
        return SvcM2Spu.getBean().info(spuId);
    }

    /**
     * 购买车列表
     */
    @SneakyThrows
    @RequestMapping("cart_list")
    public XReturn cartList() {
        List<Map<String, Object>> listData = SvcM2Cart.getBean().list(getOpenid());

        XReturn r = XReturn.getR(0);
        r.setData("list_data", listData);

        return r;
    }

    /**
     * 添加购买车
     */
    @RequestMapping("cart_add")
    public XReturn cartAdd() {
        InputData inputData = InputData.fromRequest();
        String skuId = inputData.input("sku_id", "");
        String count = inputData.input("count", "0");

        if (XStr.isNullOrEmpty(skuId)) {
            return EnumSys.MISS_VAL.getR("miss sku_id");
        }

        return SvcM2Cart.getBean().add(getOpenid(), skuId, Integer.parseInt(count));
    }

    /**
     * 删除购买车
     */
    @RequestMapping("cart_del")
    @Transactional
    public XReturn cartDel() {
        return SvcM2Cart.getBean().delete(getIds());
    }
}
